package com.base.controller.authority;

import com.base.config.Constant;
import com.base.model.LoginModel;
import com.base.model.authority.*;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.zh_new.annotation.RouteBind;
import com.zh_new.controller.BaseController;
import com.zh_new.util.Pwd;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RouteBind(path = "/Main/QxUser", viewPath = "System/Authority/User")
public class UserController extends BaseController {

	public void main() {
		String select = "select u.id, u.dlid, u.name, u.zwxx, u.usable, d.fname as dname, d.dlvl, u.lo, u.pid, p.pname,u.sex,u.staff_id,u.bank_name,u.bank_account ";
		/*int deparment_id = 0;*/
		String username = "";
		int pageSize = Constant.PAGE_SIZE;
		int pageNumber = 1;
		if (null != getPara("name") && !"".equals(getPara("name").trim())) {
			username = getPara("name").trim();
		}
		try {
			/*if (null != getPara("deparment_id") && !"".equals(getPara("deparment_id").trim())) {
				deparment_id = getParaToInt("deparment_id");
			}*/
			if (null != getPara("numPerPage") && !"".equals(getPara("numPerPage").trim())) {
				pageSize = getParaToInt("numPerPage");
			}
			if (pageSize <= 0) {
				throw new Exception();
			}
			if (null != getPara("pageNum") && !"".equals(getPara("pageNum").trim())) {
				pageNumber = getParaToInt("pageNum");
			}
			if (pageNumber <= 0) {
				throw new Exception();
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的查询参数有误，请检查后重新提交！\"}");
			return;
		}
		String sqlExceptSelect = "from t_user u left join t_department d on u.d_id=d.id LEFT JOIN t_position p ON u.pid=p.id where 1=1 ";
		/*if (0 < deparment_id) {
			sqlExceptSelect += " and d.id=" + deparment_id;
			setAttr("deparment_id", deparment_id + "");
		}*/
		if (!"".equals(username)) {
			sqlExceptSelect += " and u.name like '%" + username + "%'";
			setAttr("username", username);
		}
		sqlExceptSelect += " order by d.dlvl, u.id ";
		getdept(getRequest());
		try {
			Page<T_User> userPage = T_User.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
			setAttr("userPage", userPage);
			if (null != userPage.getList() && 0 < userPage.getList().size()) {
				Map<String, String> rnameMap = new HashMap<String, String>();
				for (int i = 0; i < userPage.getList().size(); i++) {
					List<T_UserRoles> userRoless = userPage.getList().get(i).getAllRoleInfo();
					if (null != userRoless && 0 < userRoless.size()) {
						StringBuffer buffer = new StringBuffer("");
						for (T_UserRoles userRoles : userRoless) {
							buffer.append("【" + userRoles.getStr("name") + "】");
						}
						rnameMap.put(userPage.getList().get(i).getInt("id") + "", buffer.substring(0));
					}
				}
				setAttr("rnameMap", rnameMap);
			}
			render("user_main.jsp");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"服务器存在错误，数据读取失败！\"}");
		}
	}

	public void addip() {
		List<T_Position> tPosition = T_Position.dao.getAllPositions();
		setAttr("tPosition", tPosition);
		render("user_add.jsp");
	}

	public void add() {
		/*if (null == T_Department.dao.findById(getParaToInt("district.id"))) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，部门信息不存在！\"}");
			return;
		}*/
		/*if (null == T_Position.dao.findById(getParaToInt("position.id"))) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，职位信息不存在！\"}");
			return;
		}*/
		if (null != T_User.dao.findFirst("select * from t_user where dlid='" + getPara("dlid").trim() + "'")) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，用户登录ID已存在！\"}");
			return;
		}
		boolean succeed;
		try {
			succeed = Db.tx(new IAtom() {
				public boolean run() throws SQLException {
					T_User user = new T_User();
                    user.set("dlid", getPara("dlid").trim());
                    user.set("name", getPara("name").trim());
                    user.set("pwd", getPara("pwd").trim());
                    user.set("usable", getParaToBoolean("usable"));
                    /*user.set("d_id", getParaToInt("district.id"));
                    user.set("pid", getParaToInt("position.id"));*/
                    /*user.set("zwxx", getPara("zwxx"));*/
                    user.set("dbstate", "0");
                    /*user.set("lo", getPara("lo"));*/
                    user.set("sex", getPara("sex"));
                    user.set("staff_id", getPara("staff_id"));
                    user.set("bank_name", getPara("bank_name"));
                    user.set("bank_account", getPara("bank_account"));
                    boolean value1 =user.save();
					boolean value2 = user.set("pwd", Pwd.encrypt(user.getInt("id") + getPara("pwd").trim())).update();
					return value1 && value2;
				}
			});
			if (succeed) {
				toDwzJson(200, "用户信息添加完成", "usermg", "", "closeCurrent");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	/**
	 * 获取部门选项信息
	 */
	public void getdept(HttpServletRequest request) {
		List<T_Department> alldepts = new ArrayList<T_Department>();
		List<T_Department> deparments = T_Department.dao.find("select * from t_department where dbstate='0' and d_pid is null");
		if (null != deparments && deparments.size() > 0) {
			List<String[]> deptstrs = new ArrayList<String[]>();
			for (T_Department dept : deparments) {
				T_Department.dao.getchilddept(dept, alldepts, deptstrs);
			}
			request.setAttribute("depts", alldepts);
			request.setAttribute("deptstrs", deptstrs);
		}
	}

	public void updateip() {
		String uid = getPara();
		if (null == uid || "".equals(uid.trim())) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\"}");
			return;
		}
		int u_id;
		try {
			u_id = Integer.parseInt(uid);
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\"}");
			return;
		}
		T_User user = T_User.dao.findById(u_id);
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		getdept(getRequest());
		Integer d_id = user.getInt("d_id");
		List<T_Position> tPosition = T_Position.dao.getAllPositions();
		setAttr("tPosition", tPosition);
		T_Department deparment = T_Department.dao.findById(d_id);
		setAttr("user", user);
		setAttr("deparment", deparment);
		render("user_update.jsp");
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void gettree() {
		List<T_Department> deparments = T_Department.dao.getpdepts();
		StringBuffer buffer = new StringBuffer("");
		if (null != deparments && 0 < deparments.size()) {
			buffer.append("<ul class=\"tree  expand\">");
			for (T_Department deparment : deparments) {
				buffer.append("<li><a href=\"javascript:\" onclick=\"$.bringBack({id:'" + deparment.getInt("id") + "'," + " districtName:'" + deparment.getStr("sname") + "'})\">"
						+ deparment.getStr("fname") + "</a>");
				Integer pid = deparment.getInt("id");
				intoDeparments(pid, buffer);
				buffer.append("</li>");
			}
			buffer.append("</ul>");
		}
		setAttr("deparments", buffer.substring(0));
		render("tree.jsp");
	}

	public void getdetree() {
		List<T_Department> departments = T_Department.dao.getpdepts();
		StringBuffer buffer = new StringBuffer("");
		if (null != departments && 0 < departments.size()) {
			buffer.append("<ul class=\"tree  expand\">");
			for (T_Department department : departments) {
				buffer.append("<li><a href=\"javascript:\" onclick=\"$.bringBack({depId:'" + department.getInt("id") + "'," + " dep:'" + department.getStr("sname") + "'})\">"
						+ department.getStr("fname") + "</a>");
				Integer pid = department.getInt("id");
				intoDeparments(pid, buffer);
				buffer.append("</li>");
			}
			buffer.append("</ul>");
		}
		setAttr("deparments", buffer.substring(0));
		render("tree.jsp");
	}

	public void intoDeparments(Integer pid, StringBuffer buffer) {
		List<T_Department> deparments = T_Department.dao.getChild1(pid);
		if (null != deparments && 0 < deparments.size()) {
			buffer.append("<ul>");
			for (T_Department deparment : deparments) {
				buffer.append("<li><a href=\"javascript:\" onclick=\"$.bringBack({id:'" + deparment.getInt("id") + "'," + " districtName:'" + deparment.getStr("sname") + "'})\">"
						+ deparment.getStr("fname") + "</a>");
				Integer pid1 = deparment.getInt("id");
				intoDeparments(pid1, buffer);
				buffer.append("</li>");
			}
			buffer.append("</ul>");
		}
	}

	public void update() {
		/*if (null == T_Department.dao.findById(getParaToInt("district.id"))) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，部门信息不存在！\"}");
			return;
		}
		if (null == T_Position.dao.findById(getParaToInt("position.id"))) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，职位信息不存在！\"}");
			return;
		}*/
		T_User user = T_User.dao.findById(getParaToInt("id"));
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		user.set("name", getPara("name").trim());
        user.set("usable", getParaToBoolean("usable"));
        /*user.set("lo", getPara("lo"));*/
        /*user.set("d_id", getParaToInt("district.id"));*/
        /*user.set("zwxx", getPara("zwxx"));*/
        /*user.set("pid", getPara("position.id"));*/
        user.set("sex", getPara("sex"));
        user.set("staff_id", getPara("staff_id"));
        user.set("bank_name", getPara("bank_name"));
        user.set("bank_account", getPara("bank_account"));
		if (null != getPara("pwd") && !"".equals(getPara("pwd").trim())) {
			user.set("pwd", Pwd.encrypt(getParaToInt("id") + getPara("pwd").trim()));
		}
		try {
			if (user.update()) {
				toDwzJson(200, "用户信息修改完成", "usermg", "", "closeCurrent");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	public void del() {
		String uid = getPara();
		if (null == uid || "".equals(uid.trim())) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\"}");
			return;
		}
		int u_id;
		try {
			u_id = Integer.parseInt(uid);
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\"}");
			return;
		}
		T_User user = T_User.dao.findById(u_id);
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		boolean flag;
		try {
			flag = user.delete();
			if (flag) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"用户信息删除成功！\", " + "\"navTabId\":\"usermg\", \"forwardUrl\":\"\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"用户信息已经被引用，用户信息删除失败！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"用户信息已经被引用，用户信息删除失败！\"}");
		}
	}

	public void rolesetip() {
		String uid = getPara();
		if (null == uid || "".equals(uid.trim())) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\", " + "\"callbackType\":\"closeCurrent\"}");
			return;
		}
		int u_id;
		try {
			u_id = Integer.parseInt(uid);
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，未选择用户信息！\"}");
			return;
		}
		T_User user = T_User.dao.findById(u_id);
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		setAttr("user", user);
		setAttr("userroles", user.getAllRoleInfo());
		setAttr("allroles", user.getSetRoles());
		render("user_roleset.jsp");
	}

	public void roleset() {
		Integer uId, priority, rId;
		try {
			uId = getParaToInt("id");
			priority = getParaToInt("priority");
			rId = getParaToInt("roleId");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (0 >= uId || 0 >= rId) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (0 >= priority) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，优先系数请设置为大于0的整数！\"}");
			return;
		}
		T_User user = T_User.dao.findById(uId);
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		T_Role role = T_Role.dao.findById(rId);
		if (null == role) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，系统角色不存在！\"}");
			return;
		}
		T_UserRoles userRoles = new T_UserRoles();
		try {
			userRoles.set("dbstate", "0").set("u_id", uId).set("r_id", rId).set("priority", priority).save();
			renderJson("{\"statusCode\":\"200\", \"message\":\"用户角色分配完成！\"," + "\"forwardUrl\":\"Main/QxUser/rolesetip/" + uId + "\", " + "\"dlid\":\"userroleset\","	+ "\"callbackType\":\"reload\"}");
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，系统角色分配失败！\"}");
		}
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void roledelete() {
		Integer urId;
		try {
			urId = getParaToInt();
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		if (0 >= urId) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，请检查后重新提交！\"}");
			return;
		}
		T_UserRoles userRoles = T_UserRoles.dao.findById(urId);
		if (null == userRoles) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"您提交的数据有误，信息不存在！\"}");
			return;
		}
		int uId = userRoles.getInt("u_id");
		try {
			if (userRoles.delete()) {
				renderJson("{\"statusCode\":\"200\", \"message\":\"用户角色删除完成！\"," + "\"forwardUrl\":\"Main/QxUser/rolesetip/" + uId + "\", " + "\"dlid\":\"userroleset\","
						+ "\"callbackType\":\"reload\"}");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，系统角色删除失败！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，系统角色删除失败！\"}");
		}
	}

	/** 修改用户密码 */
	@ClearInterceptor(ClearLayer.ALL)
	public void pwordset() {
		T_User user = T_User.dao.findById(getParaToInt());
		if (null == user) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的数据有误，用户信息不存在！\"}");
			return;
		}
		if ("".equals(getPara("oldpassword")) || null == getPara("oldpassword")) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"请输入密码！\"}");
			return;
		}
		String oldpassword = getPara("oldpassword");
		if (!user.get("pwd").equals(Pwd.encrypt(user.get("id") + oldpassword))) {
			renderJson("{\"statusCode\":\"300\", \"message\":\"您提交的密码有误，请重新输入！\"}");
			return;
		}
		if (null != getPara("password") && !"".equals(getPara("password").trim())) {
			user.set("pwd", Pwd.encrypt(getParaToInt() + getPara("password").trim()));
		}
		try {
			if (user.update()) {
				toDwzJson(200, "用户密码修改成功！", "", "pwdset", "closeCurrent");
			} else {
				renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
			}
		} catch (Exception e) {
			renderJson("{\"statusCode\":\"300\", " + "\"message\":\"数据处理存在错误，请检查后重新提交！\"}");
		}
	}

	@ClearInterceptor(ClearLayer.ALL)
	public void pwordsetip() {
		LoginModel loginModel = getSessionAttr("loginModel");
		Integer id = loginModel.getUserId();
		T_User user = T_User.dao.findById(id);
		setAttr("user", user);
		render("user_pwordset.jsp");
	}
}
